#include "ParameterParser.h"

bool ParameterParser::instanceFlag = false;
bool ParameterParser::vectorLoadedFlag = false;
string ParameterParser::filename = "";
ParameterParser* ParameterParser::instance = NULL;

std::vector<hash_map<string, string, hash<string>, eqstr> > 
    ParameterParser::the_vector;

ParameterParser*  ParameterParser::getInstance()
{
    if(!instanceFlag)
    {
        instance = new ParameterParser();
        instanceFlag = true;
    }
    return instance;
}

ParameterParser::ParameterParser()
{
    //empty constructor
}

ParameterParser::~ParameterParser()
{
    //empty destructor
}

string ParameterParser::parseParameter(string to_get, int thread_number)
{
  string result;
  hash_map<string, string, hash<string>, eqstr> temp_h;
  hash_map<string, string, hash<string>, eqstr>::iterator iterator;
  
  if(!vectorLoadedFlag)
  {
    std::cerr << "Main configuration file not loaded" << std::endl;
    return "";
  }
   
  if(thread_number < (int)(the_vector.size()-1) )
  {
    temp_h = the_vector.at(thread_number+1);  //increment by 1 cause first is global hash_map
  }
  else
  { //thread_number not found
    std::cerr << "Thread not found" << std::endl;
    return "";
  }
    iterator = temp_h.find(to_get);
  
  if (iterator != temp_h.end())
  { //to_get was found in the thread itself
    result = iterator->second;
    if(result != "")
    {
        return result;
    }
  }
  
  //to_get was not found or empty in the thread itself, now searching in global
  hash_map<string, string, hash<string>, eqstr> global;
  global = the_vector[0];
  iterator = global.find(to_get);
  
  if (iterator != global.end())
  { //to_get was found in the global hash_map
    result = iterator->second;
  }
  else
  {
    std::cerr << "Parameter '"<< to_get <<"' not found" << std::endl;
    return "";
  }
  
  return result;
    
}

void ParameterParser::loadNewFile(string url)
{
    xMLLoader.XMLLoad(the_vector,url);
    filename = url;
    vectorLoadedFlag = true;
}
string  ParameterParser::getScenarioFilename()
{
    if(vectorLoadedFlag)
    {
        return filename;
    }
    else
    {
        std::cerr << "Main configuration file not loaded" << std::endl;
        return "";
    }
}

uint ParameterParser::getNumberOfThreads()
{
    if(vectorLoadedFlag)
    {
        return the_vector.size() - 1 ;
    }
    else
    {
        std::cerr << "Main configuration file not loaded" << std::endl;
        return 0;
    }
}
        
bool ParameterParser::getVectorLoadedFlag()
{
    return vectorLoadedFlag;
}
